<?php
namespace api\app\controller;
use api\app\model\UsersModel;
use api\app\validate\UsersValidate;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use think\File;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class UsersController extends RestBaseController
{
    public function register()
    {
        // 获取请求数据
        $data = Request::post();
        $validate = new UsersValidate();
        $res = $validate->scene('register')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }

        // 检查手机号是否已存在
        if (UsersModel::where('mobile', $data['mobile'])->find()) {
            return error('手机号已被注册');
        }

         //验证短信验证码
//        if (!checkSmsCode($data['mobile'], $data['code'])) {
//            return error('验证码错误或已过期');
//        }
        // 创建用户
        try {
            $user = UsersModel::create($data);
            // 生成 token
            $token = signToken($user->id, $user->mobile); // 确保调用正确的 signToken 函数
            return json(['status' => 'success', 'data' => $user->toArray(), 'token' => $token]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
    public function login()
    {
        $data = Request::post();
        $validate = new UsersValidate();
        $res = $validate->scene('register')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        // 获取用户信息
        $user = UsersModel::where('mobile', $data['mobile'])->find();
        if (!$user) {
            return error('账号不存在');
        }
        // 验证短信验证码
//        if (!checkSmsCode($data['mobile'], $data['code'])) {
//            return error('验证码错误或已过期');
//        }
        // 生成 token
        $token = signToken($user->id, $user->mobile);
        return json(['status' => 'success', 'data' => ['token' => $token], 'message' => '登录成功']);
    }
    public function sendSmsCode()
    {
        $mobile = input('post.mobile');
        return SendCode($mobile);
    }
    //输出个人信息
    public function getUserList()
    {
        $header = request()->header();
        if(!isset($header['token']) || empty($header['token'])){
            $this->error('缺少token');
        }
        $key = new Key('key', 'HS256');
        try {
            $res = JWT::decode($header['token'],$key);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
        //第几页
        $page = input('page/d',1);
        //每页数据
        $pageSize = input('page_size/d',10);
        //排序
        $orderList = input('order_list/s','id');
        $orderType = input('order_type/s','DESC');

        $list = UsersModel::order($orderList,$orderType)
            ->field('id,image,user_name,mobile')
            ->page($page,$pageSize)
            ->where('id',$res->data->user_id)
            ->find();
        $list['image'] = request()->domain() . '/storage/' . $list['image'];
        return success('查询成功',$list);
    }
    //添加图片
    public function addImage()
    {
        $mobile = input('mobile');
        $image = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image',$image);

        if(!$mobile){
            return error('请输入手机号');
        }

        $image2 =   request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result;
        $addImage = UsersModel::where('mobile','=',$mobile)->find();
        if (!$addImage){
            $this->error('未查询到数据');
        }

        $addImage->image = $image2;

        if ($addImage->save()){
            return json(['code' => 1,
                'msg' => "上传成功" ,
                'data' => [
                    'url' => $image2,
                ]
            ]);
        }else{
            return json(['code' => 0,'msg' => "上传失败" , 'data' => null]);
        }

    }
//修改用户
    public function editUser()
    {
        $data = input('post.');
        //判断器
        $validate = new UsersValidate();
        $result = $validate->scene('login')->check($data);
        //判断手机号是否相同
        $existMobile = UsersModel::where('mobile','=',$data['mobile'])->find();
        if ($existMobile){
            return error('手机号存在相同');
        }
        //去除image数据
        unset($data['image']);
        //修改图片
        $image = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image',$image);
        $image2 =   request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result;

        //修改数据库
        $edit = UsersModel::where('id','=',$data['id'])->find();
        if (!$edit){
            $this->error('未查询到数据');
        }

        $edit->mobile = $data['mobile'];
        $edit->image = $image2;
        $edit->user_name = $data['user_name'];
        if ($edit->save()){
            return success('修改成功');
        }else{
            return error('修改失败');
        }
    }

}
